from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Notice, Comment, NoticeReadStatus

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'first_name']

class CommentSerializer(serializers.ModelSerializer):
    author = UserSerializer(source='publisher', read_only=True)
    is_liked = serializers.SerializerMethodField()
    likes_count = serializers.SerializerMethodField()

    class Meta:
        model = Comment
        fields = ['id', 'content', 'created_at', 'author', 'is_liked', 'likes_count']
        read_only_fields = ['created_at']

    def get_is_liked(self, obj):
        request = self.context.get('request')
        if request and request.user.is_authenticated:
            return obj.likes.filter(id=request.user.id).exists()
        return False

    def get_likes_count(self, obj):
        return obj.likes.count()

class NoticeSerializer(serializers.ModelSerializer):
    author = UserSerializer(source='publisher', read_only=True)
    is_read = serializers.SerializerMethodField()
    is_liked = serializers.SerializerMethodField()
    likes_count = serializers.SerializerMethodField()
    comments_count = serializers.SerializerMethodField()

    class Meta:
        model = Notice
        fields = ['id', 'title', 'content', 'notice_type', 'author', 'created_at', 
                 'is_read', 'is_liked', 'likes_count', 'comments_count']
        read_only_fields = ['created_at']

    def get_is_read(self, obj):
        request = self.context.get('request')
        if request and request.user.is_authenticated:
            read_status = obj.read_statuses.filter(user=request.user).first()
            return read_status.is_read if read_status else False
        return False

    def get_is_liked(self, obj):
        request = self.context.get('request')
        if request and request.user.is_authenticated:
            return obj.likes.filter(id=request.user.id).exists()
        return False

    def get_likes_count(self, obj):
        return obj.likes.count()

    def get_comments_count(self, obj):
        return obj.comments.count()